import React, { useEffect, useState } from 'react';

interface DebugStats {
	connectionType: string;
	iceState: string;
	bitrateSend: number;
	bitrateRecv: number;
	rtt: number;
	resolutionSend: string;
	resolutionRecv: string;
}

interface Props {
	pc: RTCPeerConnection;
	role: string;
}

const RtcDebugPanel: React.FC<Props> = ({ pc, role }) => {
	const [stats, setStats] = useState<DebugStats>({
		connectionType: 'unknown',
		iceState: 'new',
		bitrateSend: 0,
		bitrateRecv: 0,
		rtt: 0,
		resolutionSend: '-',
		resolutionRecv: '-',
	});

	useEffect(() => {
		const interval = setInterval(async () => {
			const reports = await pc.getStats();
	
			let connectionType = 'unknown';
			let bitrateSend = 0;
			let bitrateRecv = 0;
			let rtt = 0;
			let resolutionSend = '-';
			let resolutionRecv = '-';

			reports.forEach((report) => {
				if (report.type === 'candidate-pair' && report.state === 'succeeded') {
					connectionType = report.localCandidateType; // host / srflx / relay
					rtt = report.currentRoundTripTime * 1000;
				}

				if (report.type === 'outbound-rtp' && report.kind === 'video') {
					bitrateSend = report.bytesSent;
					if (report.frameWidth && report.frameHeight) {
						resolutionSend = `${report.frameWidth}x${report.frameHeight}`;
					}
				}

				if (report.type === 'inbound-rtp' && report.kind === 'video') {
					bitrateRecv = report.bytesReceived;
					if (report.frameWidth && report.frameHeight) {
						resolutionRecv = `${report.frameWidth}x${report.frameHeight}`;
					}
				}
			});

			setStats({
				connectionType,
				iceState: pc.iceConnectionState,
				bitrateSend,
				bitrateRecv,
				rtt,
				resolutionSend,
				resolutionRecv,
			});
		}, 1000);
		

		return () => clearInterval(interval);
	}, [pc]);

	return (
		<div
			style={{
				background: '#111',
				color: '#eee',
				padding: '1rem',
				fontFamily: 'monospace',
			}}
		>
			<h3>{role === 'caller' ? '🟢 我发起的连接' : '🔵 对方发起的连接'}</h3>
			<h3>🔍 WebRTC 调试面板</h3>
			<p>
				ICE 状态：<strong>{stats.iceState}</strong>
			</p>
			<p>
				连接类型：<strong>{stats.connectionType}</strong>{' '}
				{stats.connectionType === 'srflx'
					? '✅ 打洞成功'
					: stats.connectionType === 'relay'
					? '🌀 使用 TURN 中继'
					: '-'}
			</p>
			<p>
				发送码率：<strong>{(stats.bitrateSend / 1024).toFixed(1)} KB</strong>
			</p>
			<p>
				接收码率：<strong>{(stats.bitrateRecv / 1024).toFixed(1)} KB</strong>
			</p>
			<p>
				RTT 延迟：<strong>{stats.rtt.toFixed(1)} ms</strong>
			</p>
			<p>
				发送分辨率：<strong>{stats.resolutionSend}</strong>
			</p>
			<p>
				接收分辨率：<strong>{stats.resolutionRecv}</strong>
			</p>
		</div>
	);
};

export default RtcDebugPanel;
